package com.atguigu.crowd.mvc.handler;

import com.atguigu.crowd.entity.Admin;
import com.atguigu.crowd.exception.LoginFailedException;
import com.atguigu.crowd.service.api.AdminService;
import com.atguigu.crowd.util.CrowdConstant;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;

/**
 * AdminHandler
 *
 * @author Chan
 * @since 2021/8/4
 */
@Controller
public class LoginHandler {

    @Autowired
    private AdminService adminService;

    /**
     * 注销
     *
     * @param session   HttpSession
     * @return  String
     */
    @RequestMapping (value = "/admin/logout")
    public String doLogout(HttpSession session) {
        session.invalidate();
        return "redirect:/admin/login";
    }

    /**
     * 登录页面
     *
     * @return String登录视图
     */
    @GetMapping("/admin/login")
    public String getLogin() {
        return "admin-login";
    }

    /**
     * 登录逻辑
     *
     * @param loginAcct String
     * @param userPswd  String
     * @param session   HttpSession
     * @return  String
     */
    @PostMapping ("/admin/login")
    public String postLogin(@RequestParam("loginAcct") String loginAcct, @RequestParam("userPswd") String userPswd,
                          HttpSession session) {

        if (StringUtils.isEmpty(loginAcct) || StringUtils.isEmpty(userPswd)) {
            throw new LoginFailedException("用户名或密码不能为空");
        }

        Admin admin = adminService.getAdminByLoginAcct(loginAcct, userPswd);

        session.setAttribute(CrowdConstant.ATTR_NAME_LOGIN_ADMIN, admin);

        return "redirect:/admin/main";
    }

    /**
     * 主页
     *
     * @return  String
     */
    @RequestMapping("/admin/main")
    public String getMain() {
        return "admin-main";
    }

}
